<template>
  <div class="rule-tree-node">
    <div
      v-if="children.length > 1"
      class="rule-logic"
    >
      <span @click="logicVal = !logicVal">{{ logicVal | logicFilter }}</span>
    </div>
    <ul class="rule-leaves">
      <li
        v-for="(child, childIndex) in children"
        :key="childIndex"
      >
        <global-rule-tree-node
          v-if="child[childrenKey] && child[childrenKey].length"
          :children-key="childrenKey"
          :node="child"
          :cascader-options="cascaderOptions"
          :common-indicator-obj="commonIndicatorObj"
          :unique-child-data="uniqueChildData"
          :disabled="disabled"
          :show-btn-group="showBtnGroup"
          :show-leaf-btn="showLeafBtn"
          @removeChild="removeChild"
        ></global-rule-tree-node>
        <template v-else>
          <div
            v-if="tagType==='customize'"
            class="rule-leaf"
          >
            <div class="rule-leaf-content">
              <el-row :gutter="20">
                <el-col :span="assignColSpan(child)">
                  <el-cascader
                    id="ruleCascader"
                    v-model="child.property"
                    :disabled="disabled"
                    :options="cascaderOptions"
                    :props="cascaderProps"
                    popper-class="rule-cascader"
                    @change="((val)=>{cascaderChange(val, child)})"
                  >
                    <template #default="{ data }">
                      <span
                        class="el-cascader-default"
                        :class="{ 'el-cascader-fc':data.code==='user_tag_group_header'||data.code==='user_group_header'||data.code==='basic_self' }"
                      >{{ data.name }}</span>
                    </template>
                  </el-cascader>
                </el-col>
                <el-col
                  v-if="child.opeationList.length"
                  :span="4"
                >
                  <el-select
                    v-model="child.condition"
                    :disabled="disabled"
                    filterable
                    placeholder="请选择"
                    @change="((val)=>{casSelectChange(val, child)})"
                  >
                    <el-option
                      v-for="item in child.opeationList"
                      :key="item.label"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col
                  v-if="showWidgets(child)"
                  :span="8"
                >
                  <global-component-library v-bind="{ data: child, disabled }"></global-component-library>
                </el-col>
                <el-col
                  v-if="child.screenArr && !disabled"
                  :span="4"
                  class="svg_screen"
                >
                  <span @click="addScreen(child)">
                    <svg-icon icon-class="screen_add"></svg-icon>添加筛选
                  </span>
                </el-col>
              </el-row>
            </div>
            <div
              v-if="!disabled&&showBtnGroup"
              class="rule-leaf-operation"
            >
              <span
                v-if="childIndex + 1 === children.length&&showLeafBtn"
                class="svg-add"
                @click="addLeaf(node)"
              >
                <svg-icon icon-class="add"></svg-icon>新增
              </span>
              <span
                class="svg-close"
                @click="removeChild(child)"
              >
                <svg-icon icon-class="delete"></svg-icon>
              </span>
            </div>
          </div>
          <div
            v-if="child.screenArr && child.screenArr.length"
            class="screen-group"
          >
            <span>并且满足</span>
            <global-rule-tree-node
              children-key="screenArr"
              :node="child"
              :cascader-options="cascaderOptions"
              :common-indicator-obj="commonIndicatorObj"
              :unique-child-data="uniqueChildData"
              :show-btn-group="showBtnGroup"
              :show-leaf-btn="showLeafBtn"
              :disabled="disabled"
            ></global-rule-tree-node>
          </div>
        </template>
      </li>
    </ul>
  </div>
</template>
<script>
import commonMixin from "@/components/RuleTree/common-mixin";
import { userMaps } from "@/components/RuleTree/opmap";
export default {
  name: 'GlobalRuleTreeNode',
  components: {},
  mixins: [commonMixin],
  props: {
    node: {
      type: Object,
      required: true
    },
    tagType: { // 区分是自定义标签与基础指标值与事件指标
      type: String,
      default: "customize"
    },
    showLeafBtn: {
      type: Boolean,
      default: true
    },
    showBtnGroup: { // 是否显示新增及删除按钮
      type: Boolean,
      default: true
    },
    cascaderOptions: {
      type: Array,
      default: () => []
    },
    commonIndicatorObj: {
      type: Object,
      default: () => ({})
    },
    uniqueChildData: {
      type: Object,
      default: () => ({})
    }
  },
  inject: ['openGoodsDialog'],
  data() {
    return {

    };
  },
  computed: {},
  async mounted() {
  },
  methods: {
    assignColSpan({ property, screenArr }) {
      const hideBtnNuM = this.showBtnGroup || screenArr ? 0 : 2
      if (property.includes('user_tag_group_header')) { return 10 + hideBtnNuM; }
      const result = property.length ? property[property.length - 1].split('#') : [];
      return result.includes('relative_pass_before') ||
        result.includes('relative_future_inside') ||
        result.includes('relative_future_after') ||
        result.includes('relative_pass_inside') ||
        result.includes('relative_pass_between') ||
        result.includes('relative_future_between') ? 12 + hideBtnNuM : 8 + hideBtnNuM;
    },
    casSelectChange(val, child) {
      const { opeationList, property } = child;
      const code = property[property.length - 1];
      const result = opeationList.find((o) => val === o.value);
      const type = result ? result.type : '';
      const tagType = this.getsqlTagType(property, code);
      this.initChangeData(child);
      // 对sql标签进行定制化
      if (tagType === 'sqlrule' && (type === 'multiple' || type === 'enum')) {
        child.type = 'input';
        return;
      }
      child.type = type;
    },
    getOptType(code, optionsArr) {
      let result = null;
      optionsArr.map((options) => {
        return { children: [options] };
      }).some(function recursion({ children }) {
        return children.some(function(child) {
          if (child.code === code) {
            result = child;
            return true;
          }
          return child.children ? recursion(child) : false;
        });
      });
      return result ? result.optType : '';
    },
    initChangeData(child) {
      child.valArray = [];
      child.valArrayName = '';
    },
    showWidgets(child) {
      if (child.type === 'multiple') {
        const val = child.property;
        return this.getsqlTagType(val, val[val.length - 1]) !== 'sqlrule';
      }
      return !!child.type;
    },
    async cascaderChange(val, child) {
      const code = val[val.length - 1];
      const optType = this.getOptType(code, this.cascaderOptions);
      // init select,input框等数据
      this.initChangeData(child);
      child.multipleList = [];
      // 对時間type进行赋值，进行区别 enum 等状态，同时对opeationList =[]
      if (optType === 'input_between' || optType === 'input_single') {
        child.opeationList = [];
        // 相对当前时间点 相对当前时间区间 赋值type为input
        child.type = optType;
        return;
      }
      // 对用户标签类目-sql标签进行单独处理
      const tagType = this.getsqlTagType(val, code);
      const userMapMatch = userMaps[optType];
      const userMapData = userMapMatch[0];
      child.condition = userMapData.value;
      child.opeationList = userMapMatch;
      if (tagType === 'sqlrule') {
        child.type = optType === 'string' || optType === 'enum' ? 'input' : userMapData.type;
        return;
      }
      // 赋值 操作符默认值 例如 选择等级，操作符默认为等于。需要放在生日后面，因为生日没有对应的optType
      child.type = userMapData.type;
      // 用户属性-除去标签存在有值没值，其他删除有值没值选项
      // 或行为满足-首次交易时间 增加 有值没值选项
      if (val.includes('user_tag_group_header') || code === 'first_order_time') {
        const exampleArr = [
          {
            label: '有值',
            value: 'exists'
          },
          {
            label: '没值',
            value: 'not exists'
          }
        ];
        child.opeationList = [...userMapMatch, ...exampleArr];
      }
      // 获取自动带出的值
      if (child.type === 'enum') {
        child.multipleList = this.commonIndicatorObj[code] || [];
      }
    },
    addScreen(child) {
      let data = [];
      this.addLeaf({ [this.childrenKey]: data }, {});
      data = data.pop();
      data.type = '';
      child.screenArr.push(data);
    },
    removeChild(child) {
      const { children } = this;
      const result = children.indexOf(child);
      if (result > -1) {
        children.splice(result, 1);
        children.length === 0 && this.$emit('removeChild', this.node);
      }
    }
  }
}
</script>

<style lang='scss'>
.rule-cascader {
  .el-cascader-menu__wrap {
    height: auto;
  }
  .el-cascader-menu__list {
    max-height: calc(100vh - 50px);
  }
  .el-cascader-default {
    color: #475669;
    padding-left: 15px;
  }
  .el-cascader-fc {
    background: #f5f8fc;
    color: #8492a6;
    line-height: 20px;
    display: block;
    padding: 5px;
    font-size: 12px;
  }
}
</style>
<style lang="scss" scoped>
@import "@/components/RuleTree/common.scss";
.rule-tree-node {
  display: flex;
  flex: 1;
  ul.rule-leaves {
    flex: 1;
    > li {
      margin-bottom: 10px;
      > .rule-leaf {
        display: flex;
        align-items: center;
        padding: 8px 0 8px 8px;
        > .rule-leaf-content {
          flex: 1;
          > .el-row {
            max-width: 100%;
            .el-col:empty {
              display: none;
            }
          }
          .svg_screen {
            text-align: center;
            > span {
              color: #475669;
              font-size: 13px;
              line-height: 32px;
              cursor: pointer;
              &:hover {
                color: #409eff;
              }
            }
          }
        }
        > .rule-leaf-operation {
          display: inline-flex;
          justify-content: flex-end;
          align-items: center;
          width: 90px;
          height: 32px;
          cursor: pointer;
          .svg-close {
            margin-left: 8px;
          }
        }
      }
      > .screen-group {
        display: flex;
        > span {
          width: 80px;
          height: 48px;
          line-height: 48px;
          color: #5e6d82;
          font-size: 13px;
          text-align: right;
        }
        ::v-deep {
          .svg-add {
            display: none;
          }
        }
      }
    }
  }
}
::v-deep {
  .el-input,
  .el-select,
  .el-cascader,
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
  }
  .el-cascader-menu__wrap {
    height: auto;
  }
}
</style>
